{% extends "base.html" %}

{% block title %}股票推荐可视化 - XX交易分析系统{% endblock %}

{% block extra_head %}
<style>
    .recommendation-card {
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s;
    }
    
    .recommendation-card:hover {
        transform: translateY(-2px);
    }
    
    .stock-table {
        font-size: 0.9rem;
    }
    
    .positive {
        color: #dc3545;
        font-weight: bold;
    }
    
    .negative {
        color: #28a745;
        font-weight: bold;
    }
    
    .energy-high {
        background-color: #fff3cd;
        color: #856404;
    }
    
    .energy-medium {
        background-color: #d1ecf1;
        color: #0c5460;
    }
    
    .energy-low {
        background-color: #f8d7da;
        color: #721c24;
    }
    
    .auto-refresh-indicator {
        position: fixed;
        top: 80px;
        right: 20px;
        z-index: 1000;
    }
    
    .sort-indicator {
        position: fixed;
        top: 120px;
        right: 20px;
        z-index: 1000;
        display: none;
    }
    
    .sortable {
        user-select: none;
        transition: background-color 0.2s;
    }
    
    .sortable:hover {
        background-color: #f8f9fa !important;
    }
    
    .sort-icon {
        opacity: 0.3;
        font-size: 0.75em;
        margin-left: 4px;
        transition: opacity 0.2s;
    }
    
    .sortable:hover .sort-icon {
        opacity: 0.7;
    }
    
    .sort-icon.active {
        opacity: 1;
        color: #0d6efd;
    }
    
    .loading-spinner {
        display: none;
    }
    
    .loading .loading-spinner {
        display: inline-block;
    }
    
</style>
{% endblock %}

{% block content %}
<!-- 自动刷新指示器 -->
<div class="auto-refresh-indicator">
    <div class="alert alert-info alert-sm d-flex align-items-center">
        <div class="loading-spinner spinner-border spinner-border-sm me-2" role="status"></div>
        <span id="refresh-interval-text">每30秒自动刷新</span>
        <span class="ms-2" id="countdown">30</span>s
    </div>
</div>

<!-- 排序指示器 -->
<div class="sort-indicator">
    <div class="alert alert-success alert-sm d-flex align-items-center">
        <i class="fas fa-sort me-2"></i>
        <span id="sort-indicator-text">默认排序</span>
    </div>
</div>

<!-- 页面标题 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center">
            <!-- <h2>
                <i class="fas fa-star text-warning me-2"></i>
                股票推荐可视化
            </h2> -->
            <div>
                <button class="btn btn-outline-primary btn-sm" id="refresh-btn">
                    <i class="fas fa-sync-alt me-1"></i>
                    手动刷新
                </button>
                <button class="btn btn-outline-secondary btn-sm ms-2" id="toggle-auto-refresh">
                    <i class="fas fa-pause me-1"></i>
                    暂停自动刷新
                </button>
                <div class="btn-group ms-2" role="group">
                    <button type="button" class="btn btn-outline-info btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                        <i class="fas fa-cog me-1"></i>
                        刷新间隔
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="setRefreshInterval(2)">2秒 (高频)</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setRefreshInterval(5)">5秒 (高频)</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setRefreshInterval(10)">10秒 (低频)</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setRefreshInterval(30)">30秒 (标准)</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setRefreshInterval(60)">60秒 (缓慢)</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="showCustomIntervalModal()">自定义...</a></li>
                    </ul>
                </div>
                <div class="btn-group ms-2" role="group">
                    <button type="button" class="btn btn-outline-success btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                        <i class="fas fa-sort me-1"></i>
                        <span id="sort-button-text">默认排序</span>
                    </button>
                    <ul class="dropdown-menu">
                        <li><h6 class="dropdown-header">按字段排序</h6></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('default', 'desc')">默认排序</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('energy_value', 'desc')">📊 能量值 ↓</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('energy_value', 'asc')">📊 能量值 ↑</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('change_percent', 'desc')">📈 涨幅 ↓</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('change_percent', 'asc')">📈 涨幅 ↑</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('volume', 'desc')">📊 成交量 ↓</a></li>
                        <li><a class="dropdown-item" href="#" onclick="setSorting('volume', 'asc')">📊 成交量 ↑</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <p class="text-muted mb-0">
            展示昨天推到zbfx的前30和后30股票，包含实时涨幅、成交量和能量值。支持按多种字段排序。
            <small class="text-info">💡 点击表头或使用排序按钮快速排序</small>
        </p>
    </div>
</div>

<!-- 数据概览 -->
<div class="row mb-4">
    <div class="col-md-2">
        <div class="card recommendation-card bg-primary text-white">
            <div class="card-body text-center">
                <h5 class="card-title">推荐日期</h5>
                <h3 id="recommendation-date">-</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card recommendation-card bg-success text-white">
            <div class="card-body text-center">
                <h5 class="card-title">前30股票</h5>
                <h3 id="top-30-count">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card recommendation-card bg-warning text-white">
            <div class="card-body text-center">
                <h5 class="card-title">后30股票</h5>
                <h3 id="bottom-30-count">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card recommendation-card bg-secondary text-white">
            <div class="card-body text-center">
                <h5 class="card-title">持续监听</h5>
                <h3 id="continuous-count">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card recommendation-card bg-dark text-white">
            <div class="card-body text-center">
                <h5 class="card-title">总股票数</h5>
                <h3 id="total-count">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card recommendation-card bg-info text-white">
            <div class="card-body text-center">
                <h5 class="card-title">更新时间</h5>
                <h6 id="last-update">{{ update_time }}</h6>
            </div>
        </div>
    </div>
</div>


<!-- 前30股票 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card recommendation-card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">
                    <i class="fas fa-arrow-up me-2"></i>
                    前30强势股票
                </h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover stock-table mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>排名</th>
                                <th>股票代码</th>
                                <th>股票名称</th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('change_percent')">
                                    当前涨幅(%) 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-change_percent"></i>
                                </th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('volume')">
                                    成交量(手) 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-volume"></i>
                                </th>
                                <th>前日成交量</th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('energy_value')">
                                    能量值 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-energy_value"></i>
                                </th>
                                <th>持仓天数</th>
                            </tr>
                        </thead>
                        <tbody id="top-30-tbody">
                            <!-- 数据将通过JavaScript填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 后30股票 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card recommendation-card">
            <div class="card-header bg-warning text-dark">
                <h5 class="mb-0">
                    <i class="fas fa-arrow-down me-2"></i>
                    后30弱势股票
                </h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover stock-table mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>排名</th>
                                <th>股票代码</th>
                                <th>股票名称</th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('change_percent')">
                                    当前涨幅(%) 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-change_percent"></i>
                                </th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('volume')">
                                    成交量(手) 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-volume"></i>
                                </th>
                                <th>前日成交量</th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('energy_value')">
                                    能量值 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-energy_value"></i>
                                </th>
                                <th>持仓天数</th>
                            </tr>
                        </thead>
                        <tbody id="bottom-30-tbody">
                            <!-- 数据将通过JavaScript填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 持续监听股票 -->
<div class="row mb-4" id="continuous-monitoring-section" style="display: none;">
    <div class="col-12">
        <div class="card recommendation-card">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0">
                    <i class="fas fa-eye me-2"></i>
                    持续监听股票
                </h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover stock-table mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>序号</th>
                                <th>股票代码</th>
                                <th>股票名称</th>
                                <th>持仓天数</th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('change_percent')">
                                    当前涨幅(%) 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-change_percent"></i>
                                </th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('volume')">
                                    成交量(手) 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-volume"></i>
                                </th>
                                <th>前日成交量</th>
                                <th class="sortable" style="cursor: pointer;" onclick="toggleSort('energy_value')">
                                    能量值 
                                    <i class="fas fa-sort sort-icon" id="sort-icon-energy_value"></i>
                                </th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="continuous-monitoring-tbody">
                            <!-- 数据将通过JavaScript填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载提示 -->
<div class="row" id="loading-indicator" style="display: none;">
    <div class="col-12 text-center">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2">正在获取最新数据...</p>
    </div>
</div>

<!-- 错误提示 -->
<div class="row" id="error-indicator" style="display: none;">
    <div class="col-12">
        <div class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>数据加载失败！</strong>
            <span id="error-message">请检查网络连接或稍后重试。</span>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<!-- 配置文件 -->
<script src="{{ url_for('static', path='js/config.js') }}"></script>
<script>
class RecommendationsPage {
    constructor() {
        // 🔧 从配置文件加载配置
        this.loadConfig();
        
        this.autoRefreshEnabled = true;
        this.refreshInterval = null;
        this.countdownInterval = null;
        this.countdown = this.REFRESH_INTERVAL;
        
        // 排序相关属性
        this.currentSortBy = 'default';
        this.currentSortOrder = 'desc';
        
        // 请求状态管理
        this.isLoading = false;
        
        this.init();
    }
    
    loadConfig() {
        // 从全局配置对象加载配置
        const config = window.RecommendationsConfig || {};
        this.REFRESH_INTERVAL = config.REFRESH_INTERVAL || 30;
        this.config = config;
    }
    
    updateConfig() {
        // 动态更新配置（用于运行时修改）
        this.loadConfig();
        this.updateRefreshIntervalText();
        this.startAutoRefresh(); // 重启自动刷新以应用新间隔
    }
    
    init() {
        this.updateRefreshIntervalText();
        this.updateSortingDisplay(); // 初始化排序状态显示
        this.bindEvents();
        this.loadData();
        this.startAutoRefresh();
    }
    
    bindEvents() {
        // 手动刷新按钮
        document.getElementById('refresh-btn').addEventListener('click', () => {
            if (!this.isLoading) {
                this.loadData();
            } else {
                showToast('数据正在加载中，请稍等...', 'info');
            }
        });
        
        // 切换自动刷新
        document.getElementById('toggle-auto-refresh').addEventListener('click', () => {
            this.toggleAutoRefresh();
        });
        
    }
    
    async loadData() {
        // 防止重复请求
        if (this.isLoading) {
            console.log('上一个请求正在进行中，跳过本次请求');
            return;
        }
        
        try {
            this.isLoading = true;
            this.showLoading(true);
            this.hideError();
            
            // 构建API URL，包含排序参数
            let url = '/api/recommendations';
            const params = new URLSearchParams();
            
            if (this.currentSortBy !== 'default') {
                params.append('sort_by', this.currentSortBy);
                params.append('sort_order', this.currentSortOrder);
            }
            
            if (params.toString()) {
                url += '?' + params.toString();
            }
            
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const apiResponse = await response.json();
            
            // 检查API响应格式
            if (!apiResponse.success) {
                throw new Error(apiResponse.msg || '获取数据失败');
            }
            
            // 使用统一格式的数据
            this.renderData(apiResponse.data);
            

            
        } catch (error) {
            console.error('加载数据失败:', error);
            this.showError(error.message);
        } finally {
            this.isLoading = false;
            this.showLoading(false);
        }
    }
    
    renderData(data) {
        // 更新概览信息
        document.getElementById('recommendation-date').textContent = data.date;
        document.getElementById('top-30-count').textContent = data.top_30.length;
        document.getElementById('bottom-30-count').textContent = data.bottom_30.length;
        document.getElementById('continuous-count').textContent = data.continuous_monitoring.length;
        document.getElementById('total-count').textContent = data.statistics?.total_stocks || (data.top_30.length + data.bottom_30.length + data.continuous_monitoring.length);
        document.getElementById('last-update').textContent = data.update_time;
        
        // 渲染前30股票
        this.renderStockTable('top-30-tbody', data.top_30, 1);
        
        // 渲染后30股票
        this.renderStockTable('bottom-30-tbody', data.bottom_30, 31);
        
        // 渲染持续监听股票
        this.renderContinuousMonitoringTable('continuous-monitoring-tbody', data.continuous_monitoring);
        
        // 控制持续监听区域显示/隐藏
        const continuousSection = document.getElementById('continuous-monitoring-section');
        if (data.continuous_monitoring && data.continuous_monitoring.length > 0) {
            continuousSection.style.display = 'block';
        } else {
            continuousSection.style.display = 'none';
        }
        
        // 初始化tooltips
        this.initTooltips();
        
        // 更新排序状态显示
        this.updateSortingDisplay();
    }
    
    renderStockTable(tbodyId, stocks, startRank) {
        const tbody = document.getElementById(tbodyId);
        tbody.innerHTML = '';
        
        stocks.forEach((stock, index) => {
            const row = document.createElement('tr');
            
            // 根据涨幅设置颜色
            const changeClass = stock.change_percent > 0 ? 'positive' : 
                               stock.change_percent < 0 ? 'negative' : '';
            
            // 根据能量值设置背景色
            const energyClass = Math.abs(stock.energy_value) > 1 ? 'energy-high' :
                               Math.abs(stock.energy_value) > 0.5 ? 'energy-medium' : 'energy-low';
            
            row.innerHTML = `
                <td><strong>${startRank + index}</strong></td>
                <td><code>${stock.code}</code></td>
                <td><strong>${stock.name || '-'}</strong></td>
                <td class="${changeClass}">${stock.change_percent}%</td>
                <td>${this.formatNumber(stock.volume)}</td>
                <td>${this.formatNumber(stock.prev_volume)}</td>
                <td class="${energyClass} px-2 py-1 rounded">${stock.energy_value}</td>
                <td>${stock.holding_days}</td>
            `;
            
            tbody.appendChild(row);
        });
    }
    
    renderContinuousMonitoringTable(tbodyId, stocks) {
        const tbody = document.getElementById(tbodyId);
        tbody.innerHTML = '';
        
        stocks.forEach((stock, index) => {
            const row = document.createElement('tr');
            
            // 根据涨幅设置颜色
            const changeClass = stock.change_percent > 0 ? 'positive' : 
                               stock.change_percent < 0 ? 'negative' : '';
            
            // 根据能量值设置背景色
            const energyClass = Math.abs(stock.energy_value) > 1 ? 'energy-high' :
                               Math.abs(stock.energy_value) > 0.5 ? 'energy-medium' : 'energy-low';
            
            // 持仓天数和状态
            const days = stock.days || stock.Days || 0;
            const isEnd = stock.isend || stock.isEnd;
            const status = isEnd === 'Y' ? '已结束' : '监听中';
            const statusClass = isEnd === 'Y' ? 'badge bg-secondary' : 'badge bg-success';
            
            row.innerHTML = `
                <td><strong>${index + 1}</strong></td>
                <td><code>${stock.code}</code></td>
                <td><strong>${stock.name || '-'}</strong></td>
                <td><span class="badge bg-info">${stock.holding_days}天</span></td>
                <td class="${changeClass}">${stock.change_percent}%</td>
                <td>${this.formatNumber(stock.volume)}</td>
                <td>${this.formatNumber(stock.prev_volume)}</td>
                <td class="${energyClass} px-2 py-1 rounded">${stock.energy_value || '-'}</td>
                <td><span class="${statusClass}">${status}</span></td>
            `;
            
            tbody.appendChild(row);
        });
    }
    
    formatNumber(num) {
        if (num === 0) return '-';
        if (num >= 100000000) {
            return (num / 100000000).toFixed(1) + '亿';
        } else if (num >= 10000) {
            return (num / 10000).toFixed(1) + '万';
        }
        return num.toLocaleString();
    }
    
    truncateText(text, maxLength) {
        if (!text) return '-';
        return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    }
    
    escapeHtml(text) {
        if (!text) return '-';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    initTooltips() {
        // 销毁现有的tooltips
        const existingTooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        existingTooltips.forEach(el => {
            const tooltip = bootstrap.Tooltip.getInstance(el);
            if (tooltip) {
                tooltip.dispose();
            }
        });
        
        // 重新初始化Bootstrap tooltips
        const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                delay: { show: 300, hide: 100 },
                placement: 'top',
                html: true
            });
        });
    }
    
    startAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
        }
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
        }
        
        if (!this.autoRefreshEnabled) return;
        
        this.countdown = this.REFRESH_INTERVAL;
        this.updateCountdown();
        
        this.countdownInterval = setInterval(() => {
            this.countdown--;
            this.updateCountdown();
            
            if (this.countdown <= 0) {
                this.loadData();
                this.countdown = this.REFRESH_INTERVAL;
            }
        }, 1000);
    }
    
    updateCountdown() {
        const countdownEl = document.getElementById('countdown');
        if (countdownEl) {
            countdownEl.textContent = this.countdown;
        }
    }
    
    updateRefreshIntervalText() {
        const textEl = document.getElementById('refresh-interval-text');
        if (textEl) {
            textEl.textContent = `每${this.REFRESH_INTERVAL}秒自动刷新`;
        }
    }
    
    toggleAutoRefresh() {
        this.autoRefreshEnabled = !this.autoRefreshEnabled;
        const btn = document.getElementById('toggle-auto-refresh');
        const indicator = document.querySelector('.auto-refresh-indicator');
        
        if (this.autoRefreshEnabled) {
            btn.innerHTML = '<i class="fas fa-pause me-1"></i>暂停自动刷新';
            indicator.style.display = 'block';
            this.startAutoRefresh();
        } else {
            btn.innerHTML = '<i class="fas fa-play me-1"></i>开启自动刷新';
            indicator.style.display = 'none';
            if (this.refreshInterval) clearInterval(this.refreshInterval);
            if (this.countdownInterval) clearInterval(this.countdownInterval);
        }
    }
    
    showLoading(show) {
        const indicator = document.getElementById('loading-indicator');
        const refreshBtn = document.getElementById('refresh-btn');
        const autoRefreshIndicator = document.querySelector('.auto-refresh-indicator');
        
        if (show) {
            indicator.style.display = 'block';
            refreshBtn.classList.add('loading');
            autoRefreshIndicator.classList.add('loading');
        } else {
            indicator.style.display = 'none';
            refreshBtn.classList.remove('loading');
            autoRefreshIndicator.classList.remove('loading');
        }
    }
    
    showError(message) {
        const errorIndicator = document.getElementById('error-indicator');
        const errorMessage = document.getElementById('error-message');
        
        errorMessage.textContent = message;
        errorIndicator.style.display = 'block';
    }
    
    hideError() {
        const errorIndicator = document.getElementById('error-indicator');
        errorIndicator.style.display = 'none';
    }
    
    // 排序相关方法
    setSorting(sortBy, sortOrder) {
        if (this.isLoading) {
            showToast('数据正在加载中，请稍后再进行排序...', 'warning');
            return;
        }
        
        this.currentSortBy = sortBy;
        this.currentSortOrder = sortOrder;
        this.updateSortingDisplay();
        this.loadData(); // 重新加载数据
    }
    
    updateSortingDisplay() {
        const sortButtonText = document.getElementById('sort-button-text');
        const sortIndicator = document.querySelector('.sort-indicator');
        const sortIndicatorText = document.getElementById('sort-indicator-text');
        
        let displayText = '默认排序';
        let showIndicator = false;
        
        if (this.currentSortBy !== 'default') {
            showIndicator = true;
            const fieldNames = {
                'energy_value': '能量值',
                'change_percent': '涨幅',
                'volume': '成交量'
            };
            
            const orderSymbol = this.currentSortOrder === 'desc' ? '↓' : '↑';
            const fieldName = fieldNames[this.currentSortBy] || this.currentSortBy;
            displayText = `${fieldName} ${orderSymbol}`;
        }
        
        if (sortButtonText) {
            sortButtonText.textContent = displayText;
        }
        
        if (sortIndicator) {
            sortIndicator.style.display = showIndicator ? 'block' : 'none';
        }
        
        if (sortIndicatorText) {
            sortIndicatorText.textContent = `按 ${displayText} 排序中`;
        }
        
        // 更新表头排序图标
        this.updateSortIcons();
    }
    
    updateSortIcons() {
        // 清除所有图标的激活状态
        const allIcons = document.querySelectorAll('.sort-icon');
        allIcons.forEach(icon => {
            icon.classList.remove('active');
            icon.className = 'fas fa-sort sort-icon';
        });
        
        // 设置当前排序字段的图标
        if (this.currentSortBy !== 'default') {
            const activeIcon = document.getElementById(`sort-icon-${this.currentSortBy}`);
            if (activeIcon) {
                activeIcon.classList.add('active');
                if (this.currentSortOrder === 'desc') {
                    activeIcon.className = 'fas fa-sort-down sort-icon active';
                } else {
                    activeIcon.className = 'fas fa-sort-up sort-icon active';
                }
            }
        }
    }
}

// 全局函数：切换排序（点击表头时调用）
function toggleSort(field) {
    if (!window.recommendationsPage) return;
    
    let newSortBy = field;
    let newSortOrder = 'desc';
    
    // 如果当前已经按这个字段排序，则切换排序方向
    if (window.recommendationsPage.currentSortBy === field) {
        if (window.recommendationsPage.currentSortOrder === 'desc') {
            newSortOrder = 'asc';
        } else {
            // 如果已经是升序，则恢复到默认排序
            newSortBy = 'default';
            newSortOrder = 'desc';
        }
    }
    
    setSorting(newSortBy, newSortOrder);
}

// 全局函数：设置排序
function setSorting(sortBy, sortOrder) {
    if (window.recommendationsPage) {
        window.recommendationsPage.setSorting(sortBy, sortOrder);
        
        // 显示成功提示
        const fieldNames = {
            'default': '默认',
            'energy_value': '能量值',
            'change_percent': '涨幅',
            'volume': '成交量'
        };
        const orderText = sortOrder === 'desc' ? '降序' : '升序';
        const fieldName = fieldNames[sortBy] || sortBy;
        const message = sortBy === 'default' ? '已恢复默认排序' : `按${fieldName}排序（${orderText}）`;
        showToast(message, 'success');
    }
}

// 全局函数：设置刷新间隔
function setRefreshInterval(seconds) {
    if (window.RecommendationsConfig) {
        window.RecommendationsConfig.REFRESH_INTERVAL = seconds;
        if (window.recommendationsPage) {
            window.recommendationsPage.updateConfig();
        }
        
        // 显示成功提示
        showToast(`刷新间隔已设置为 ${seconds} 秒`, 'success');
    }
}

// 全局函数：显示自定义间隔模态框
function showCustomIntervalModal() {
    const interval = prompt('请输入刷新间隔（秒）:', window.RecommendationsConfig?.REFRESH_INTERVAL || 30);
    if (interval && !isNaN(interval) && interval > 0) {
        setRefreshInterval(parseInt(interval));
    }
}

// 简单的Toast提示函数
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} position-fixed`;
    toast.style.cssText = 'top: 100px; right: 20px; z-index: 9999; min-width: 250px;';
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : 'info'}-circle me-2"></i>
        ${message}
    `;
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.recommendationsPage = new RecommendationsPage();
});
</script>
{% endblock %}